﻿using System;
using System.Linq;
using System.Data.Linq;
using System.Collections.Generic;
using System.Text;
using HR.Appointments.DataLayer;
using HR.Appointments.Service.Tools;

namespace HR.Appointments.Service.DataAccessLayer.DLinq
{
    internal class OpenHoursDAO : IOpenHoursDAO
    {
        #region IOpenHoursDAO Members

        public OpenHoursEntity GetByDate(int companyId, DateTime date)
        {
            using (DAODataContext ctx = new DAODataContext())
            {
                var sql = 
                    from o in ctx.OpenHours
                    join cmp in ctx.Companies on o.CompanyId equals cmp.CompanyId
                    where o.CompanyId == companyId
                        && o.DayId == DateUtils.DayOfWeekToInt(date.DayOfWeek)
                        && !cmp.EndDate.HasValue
                          select o;

                return OpenHoursEntity.Load(sql.FirstOrDefault());
            }
        }
        public List<OpenHoursEntity> GetByCompany(int companyId)
        {
            var result = new List<OpenHoursEntity>();
            using (DAODataContext ctx = new DAODataContext())
            {

                var sql =
                    from o in ctx.OpenHours
                    join cmp in ctx.Companies on o.CompanyId equals cmp.CompanyId
                    where o.CompanyId == companyId
                    && !cmp.EndDate.HasValue
                        
                    select o;
                foreach (OpenHour row in sql)
                {
                    result.Add(OpenHoursEntity.Load(row));
                }
            }
            return result;
        }

        public void Commit(OpenHoursEntity openhour)
        {
            using (DAODataContext ctx = new DAODataContext())
            {
                var sql = from data in ctx.OpenHours
                          where data.CompanyId == openhour.CompanyId
                          && data.DayId == openhour.DayId
                          select data;

                if(sql.Count() != 0)
                {
                    OpenHour row = openhour.ToData(sql.FirstOrDefault());
                }
                else
                {
                    ctx.OpenHours.InsertOnSubmit(openhour.ToData(null));
                }
                ctx.SubmitChanges();
            }
        }

        #endregion
    }
}
